<template>
  <el-switch
    v-model="selectValue"
    :active-value="activeValue"
    :before-change="onBeforeChange"
    :disabled="disabled"
    :inactive-value="inactiveValue"
    @change="onHandleChange"
  />
</template>

<script>
import { postRequest } from "@/api/mains.ts";
import { confirm } from "@/utils/MessageUtils";

export default defineComponent({
  name: "CommonSwitch",
  props: {
    modelValue: {
      type: [Number, String, Boolean],
      default: ""
    },
    activeUrl: {
      type: String,
      default: ""
    },
    inactiveUrl: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    },
    activeValue: {
      type: [Number, String, Boolean],
      default: "1"
    },
    inactiveValue: {
      type: [Number, String, Boolean],
      default: "0"
    },
    keyValue: {
      type: Array,
      default: () => []
    },
    id: {
      type: String,
      default: ""
    }
  },
  emits: {
    "update:model-value": null,
    change: null
  },

  setup(props, { emit }) {
    const selectValue = ref(props.modelValue);
    if (typeof props.activeValue === "boolean") selectValue.value = false;
    let initFlag = true;

    const onBeforeChange = () => {
      const { activeUrl, inactiveUrl } = props;
      if (!activeUrl && !inactiveUrl) {
        if (initFlag) initFlag = false;
        return true;
      }
      return new Promise(resolve => {
        confirm(
          "确定要改变当前状态吗",
          async () => {
            if (initFlag) initFlag = false;
            resolve(true);
          },
          async () => {
            resolve(false);
          }
        );
      });
    };

    const onHandleChange = async value => {
      if (initFlag) {
        initFlag = true;
        return;
      }
      const { activeUrl, inactiveUrl } = props;
      if (!activeUrl && !inactiveUrl) {
        emit("update:model-value", value);
        emit("change", value);
        return;
      }

      const key = props.keyValue[0] || "status";
      const url = value === props.activeValue ? activeUrl : inactiveUrl;
      const res = await postRequest(url, {
        id: props.id,
        [key]: value
      });
      if (res.code == 200) {
        emit("update:model-value", value);
        emit("change", value);
      } else {
        selectValue.value = props.modelValue;
      }
    };

    watch(
      () => props.modelValue,
      newVal => {
        if (newVal != selectValue.value) {
          selectValue.value = newVal;
        }
      }
    );

    return {
      selectValue,
      onBeforeChange,
      onHandleChange
    };
  }
});
</script>

<style lang="scss" scoped></style>
